<?php
/**
 * Created by PhpStorm.
 * Script Name: Mpblack.php
 * Create: 2023/3/3 8:50
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;


use app\common\service\Tenant as TenantService;
use plugin\wechat\app\model\MpFollow as FollowM;
use plugin\wechat\app\model\MpFollowBlack;
use plugin\wechat\app\service\MpFollowBlack as BlackService;
use Support\Request;

class Mpblack extends MpBase
{
    /**
     * @var MpFollowBlack
     */
    protected $model;
    /**
     * @var FollowM
     */
    private FollowM $followM;
    public function __construct()
    {
        parent::__construct();
        $this->followM = new FollowM();
        $this->model = new MpFollowBlack();
    }

    public function index(Request $request)
    {
        $mp_info = $request->mpInfo;
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere('black'),
                $this->mpIdWhere('black', $mp_info)
            ];
            !empty($post_data['search_key']) && $where[] = [
                'follow.nickname|follow.openid|follow.remark', 'like', '%' . $post_data['search_key'] . '%'
            ];
            $query = $this->model->alias('black')
                ->join($request->plugin.'_mp_follow follow', 'follow.openid=black.openid')
                ->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('black.id', 'desc')
                    ->field(['follow.*', 'black.create_time'])
                    ->select();
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '根据昵称/备注/openid搜索']
        ])
            ->addTopButton('self', ['class'=>'layui-btn-normal','text' => '同步黑名单数据', 'href' => url('pullpost'), 'data-ajax' => true, 'data-confirm' => true])
            ->addTableColumn(['title' => 'openid', 'field' => 'openid',  'minWidth' => 100])
            ->addTableColumn(['title' => '昵称', 'field' => 'nickname', 'minWidth' => 100])
            ->addTableColumn(['title' => '头像', 'field' => 'headimgurl', 'type' => 'picture', 'minWidth' => 100])
            ->addTableColumn(['title' => '备注', 'field' => 'remark', 'minWidth' => 70])
            ->addTableColumn(['title' => '拉黑时间', 'field' => 'create_time',  'minWidth' => 180])
            ->addTableColumn(['title' => '操作', 'minWidth' => 160, 'type' => 'toolbar'])
            ->addRightButton('delete', ['text' => '取消黑名单', 'href' => url('unblockPost', ['openid' => '__data_openid__']), 'data-ajax'=>true, 'data-confirm' => true]);

        return $builder->show();
    }

    /**
     * 取消拉黑
     * @param Request $request
     * @return \support\Response
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function unblockPost(Request $request){
        if($request->isPost()){
            $mp_info = $request->mpInfo;
            $openid = input('openid', '');
            if(! $data = $this->model->where([$this->tenantWhere(), $this->mpIdWhere()])->where('openid', $openid)->find()){
                return $this->error('数据不存在');
            }
            if(is_string($res = BlackService::unblock($openid, $mp_info))){
                return $this->error($res);
            }
            return $this->success('操作成功！');
        }
    }

    /**
     * 同步黑名单
     * @param Request $request
     * @return \support\Response
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function pullPost(Request $request)
    {
        if ($request->isPost()) {
            $mp_info = $request->mpInfo;
            $begin_openid = null;
            if(is_string($res = BlackService::blackList($begin_openid, $mp_info))){
                return $this->error($res);
            }

            if(!empty($res['count'])){
                foreach ($res['data']['openid'] as $openid){
                    if (!$this->model->where([$this->tenantWhere(), $this->mpIdWhere()])
                        ->where('openid', $openid)
                        ->count()) {
                        $this->model->createOne([
                            'mp_id' => $mp_info['id'],
                            'company_id' => $mp_info['company_id'],
                            'openid' => $openid,
                        ]);
                    }
                }
            }

            return $this->success('同步成功！');
        }
    }
}